<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Jobs;

use App\Models\ProductOrder;
use App\Service\Pools\DividendService;
use App\Service\Product\ProductOrderService;
use App\Service\User\PerformanceService;
use App\Service\User\WalletAccountService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class CartOrderPlacementJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $tries = 5;

    public $maxExceptions = 3;

    public $backoff = [30, 60, 300, 600, 1800];

    public $timeout = 300;

    public $user;

    public $cart;

    public $method;

    /**
     * 解除任务唯一锁的秒数.
     *
     * @var int
     */
    public $uniqueFor = 3600;

    public function __construct($user, $cart, $method)
    {
        $this->user = $user;
        $this->cart = $cart;
        $this->method = $method;
    }

    /**
     * 任务的 unique ID (唯一ID).
     *
     * @return string
     */
    public function uniqueId()
    {
        return $this->user->id;
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
        $this->cart->each(function ($item) {
            //减少库存
            $productSku = $item->product->sku;
            [$key,$sku] = searchArrayInMulti($item->sku, $productSku['sku'], ['stock']);
            $amount = bcmul($sku['member_price'], $item->quantity, 2);

            $wall = WalletAccountService::make()->consumption($this->user->id, $amount);
            if (! $wall) {
                Log::channel('cart_order_error')->info(sprintf('批量下单余额不足,用户ID:%s 购物车id:%s', $this->user->id, $item->id));
                return false;
            }
            $sku['stock'] = $sku['stock'] - $item->quantity;
            $productSku['sku'][$key] = $sku;
            $item->product->sku = json_encode($productSku);
            $item->product->stock -= $item->quantity;
            $item->product->sold_num += $item->quantity;
            $item->push();
            $productOrder = ProductOrder::query()->create([
                'order_no' => genOrderNumber('P'),
                'user_id' => $this->user->id,
                'product_id' => $item->product->id,
                'type' => 1,
                'total_amount' => $amount,
                'price' => $sku['member_price'],
                'number' => $item->quantity,
                'sku' => $sku,
                'method' => $this->method,
                'status' => 3,
            ]);
            ProductOrderService::make()->placeAnOrder(
                $this->user,
                $productOrder,
                $this->method,
            );
            //分红池
            DividendService::make()->injectFunds($amount, 2); //进入分红池

            //用户树收益
            PerformanceService::make()->userTreeRevenue($this->user, $amount);
            //业绩奖励
            PerformanceService::make()->performanceReward($this->user, $amount);
            $this->user->increment('inject_integral', $amount * 2);
            $item->delete();
        });
    }
}
